package sivin.uikit.framework

import android.content.pm.PackageManager
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume

class PermissionManager(private val activity: ComponentActivity) {

    private var continuation: Continuation<List<String>>? = null

    private val permissionsLauncher = activity.registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        continuation?.resume(permissions.filterNot { it.value }.keys.toList())
    }

    suspend fun checkAndRequest(permissions: Array<String>): List<String> {
        continuation = null
        val deniedPermissions = permissions.filter {
            ContextCompat.checkSelfPermission(activity, it) != PackageManager.PERMISSION_GRANTED
        }
        if (deniedPermissions.isEmpty()) {
            return emptyList()
        }
        val deniedAfterRequest = suspendCancellableCoroutine { cont ->
            continuation = cont
            permissionsLauncher.launch(deniedPermissions.toTypedArray())
        }
        continuation = null
        return deniedAfterRequest
    }
}